package com.aneliya.proxy;

import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

import com.aneliya.command.chatWindow.UpdateMessagesCommand;
import com.aneliya.framework.mvc.Facade;
import com.aneliya.framework.mvc.controller.MVCEvent;
import com.aneliya.framework.mvc.model.Proxy;
import com.aneliya.history.HistoryManager;
import com.aneliya.model.Message;
import com.aneliya.model.MessageType;

public class MessagesProxy extends Proxy {
	public static final String UPDATE_MESSAGES_EVENT = "updateMessages";
	public static final int MESSAGE_HISTORY_SIZE = 25;
	
	private ArrayList<Message> messages;
	public ArrayList<Message> getMessages() {
		return messages;
	}
	
	private ArrayList<UUID> messagesTokens;

	public MessagesProxy() throws Exception {
		name = "MessagesProxy";
		facade = Facade.getInstance();
		
		messages = new ArrayList<Message>();
		messagesTokens = new ArrayList<UUID>();
		
		initializeCommands();
	}

	private void initializeCommands() throws Exception {
		facade.registerCommand(UPDATE_MESSAGES_EVENT, UpdateMessagesCommand.class);
	}
	
	public void sendMessage(String message) throws Exception {
		UserProxy userProxy = (UserProxy) facade.retrieveProxy("UserProxy");
		Message sendMessage = new Message(userProxy.getAuthenticatedUser().getUsername(), message);
		sendMessage.setMessageType(MessageType.TEXT);
		
		messagesTokens.add(sendMessage.getToken());
		
		receiveMessage(sendMessage, false);
		
		ServerProxy serverProxy = (ServerProxy) facade.retrieveProxy("ServerProxy");
		serverProxy.sendMessage(sendMessage);
	}
	
	public void receiveMessage(Message message, Boolean checkToken) throws InstantiationException, IllegalAccessException {
		if (checkToken) {
			int tokenIndex = messagesTokens.indexOf(message.getToken());
			if (tokenIndex != -1) {
				messagesTokens.remove(tokenIndex);
				return;
			}
		}
		
		setDateOnMessage(message);
		
		messages.add(message);
		facade.dispatchMVCEvent(new MVCEvent(this, UPDATE_MESSAGES_EVENT, null));
	}
	
	public void retrieveHistory() throws Exception {
		UserProxy userProxy = (UserProxy)facade.retrieveProxy("UserProxy");
		HistoryManager.getInstance().retrieveArrayList(
				userProxy.getAuthenticatedUser().getUsername(), messages);
		facade.dispatchMVCEvent(new MVCEvent(
				userProxy.getAuthenticatedUser().getUsername(), UPDATE_MESSAGES_EVENT, null));
	}
	
	public void saveHistory() throws Exception {
		UserProxy userProxy = (UserProxy)facade.retrieveProxy("UserProxy");
		HistoryManager.getInstance().saveArrayList(
				userProxy.getAuthenticatedUser().getUsername(), messages, MESSAGE_HISTORY_SIZE);
	}
	
	private void setDateOnMessage(Message message) {
		message.setDate(new Date());
	}

}
